<template>
  <el-dialog
    :modelValue="visible"
    @update:modelValue="$emit('update:visible', $event)"
    title="创建订单"
    width="500px"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <div class="order-dialog-content">
      <!-- 商品信息区域 -->
      <div class="product-info">
        <div class="product-image">
          <el-image 
            :src="productInfo.image || productInfo.images?.[0]" 
            fit="cover" 
            alt="商品图片"
          />
        </div>
        <div class="product-details">
          <h3 class="product-title">{{ productInfo.title || productInfo.name }}</h3>
          <div class="product-price">¥{{ productInfo.price?.toFixed(2) }}</div>
        </div>
      </div>

      <!-- 订单信息表单 -->
      <el-form :model="orderForm" label-width="100px" class="order-form">
        <el-form-item label="交易地点" required>
          <el-input 
            v-model="orderForm.transactionLocation" 
            placeholder="请输入交易地点" 
            maxlength="50"
          />
        </el-form-item>

        <el-form-item label="备注信息">
          <el-input 
            v-model="orderForm.remark" 
            type="textarea" 
            rows="3" 
            placeholder="有什么想告诉卖家的?"
          />
        </el-form-item>
      </el-form>

      <!-- 订单金额 -->
      <div class="order-price-section">
        <div class="price-item">
          <span>商品金额</span>
          <span class="amount">¥{{ productInfo.price?.toFixed(2) }}</span>
        </div>
        <div class="price-item">
          <span>实付款</span>
          <span class="total-amount">¥{{ productInfo.price?.toFixed(2) }}</span>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('update:visible', false)">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleCreateOrder" 
          :loading="loading"
        >
          付款
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { createOrder } from '@/api/order';
import { useUserStore } from '@/stores/user';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  productInfo: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['update:visible', 'orderCreated']);

const userStore = useUserStore();
const loading = ref(false);

// 常用交易地点
const commonLocations = [
  { value: '校内图书馆', label: '校内图书馆' },
  { value: '校内食堂', label: '校内食堂' },
  { value: '校内宿舍区', label: '校内宿舍区' },
  { value: '校门口', label: '校门口' },
  { value: '教学楼', label: '教学楼' }
];

// 订单表单数据
const orderForm = ref({
  productId: props.productInfo?.id || 0,
  transactionLocation: '',
  remark: ''
});

// 监听visible变化，当弹窗关闭时重置表单
watch(() => props.visible, (val) => {
  console.log('Dialog visible changed:', val);
  // 当弹窗关闭时，重置表单
  if (!val) {
    resetForm();
  }
});

// 监听productInfo变化更新表单数据
watch(() => props.productInfo, (newVal) => {
  console.log('productInfo changed:', newVal);
  if (newVal && newVal.id) {
    orderForm.value.productId = newVal.id;
  }
}, { deep: true });

// 重置表单
const resetForm = () => {
  orderForm.value = {
    productId: props.productInfo?.id || 0,
    transactionLocation: '',
    remark: ''
  };
};

// 提交订单
const handleCreateOrder = async () => {
  console.log('点击付款按钮');
  
  if (!orderForm.value.transactionLocation) {
    ElMessage.warning('请填写交易地点');
    return;
  }

  if (!props.productInfo?.id) {
    ElMessage.warning('商品信息不完整');
    return;
  }

  try {
    loading.value = true;
    console.log('准备提交订单，数据：', {
      productId: props.productInfo.id,
      paymentMethod: '线下交易',
      transactionLocation: orderForm.value.transactionLocation,
      remark: orderForm.value.remark || ''
    });
    
    const data = {
      productId: props.productInfo.id,
      paymentMethod: '线下交易',
      transactionLocation: orderForm.value.transactionLocation,
      remark: orderForm.value.remark || ''
    };
    
    const response = await createOrder(data);
    console.log('订单创建响应：', response);
    
    if (response.code === 200) {
      ElMessage.success('订单创建成功');
      emit('update:visible', false);
      emit('orderCreated', response.data);
    } else {
      ElMessage.error(response.message || '订单创建失败');
    }
  } catch (error) {
    console.error('创建订单失败:', error);
    ElMessage.error('订单创建失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.order-dialog-content {
  padding: 0 15px;
}

.product-info {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.product-image {
  width: 80px;
  height: 80px;
  overflow: hidden;
  border-radius: 8px;
  flex-shrink: 0;
}

.product-image :deep(.el-image) {
  width: 100%;
  height: 100%;
}

.product-details {
  flex: 1;
  overflow: hidden;
}

.product-title {
  font-size: 16px;
  color: #333;
  margin: 0 0 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  font-size: 18px;
  color: #ff6b6b;
  font-weight: bold;
}

.order-form {
  margin-bottom: 20px;
}

.order-price-section {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.price-item:last-child {
  margin-bottom: 0;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
}

.amount {
  color: #333;
  font-weight: 500;
}

.total-amount {
  color: #ff6b6b;
  font-weight: bold;
  font-size: 18px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 